<?php

namespace app\service;

use app\dao\ClubDao;
use think\facade\Log;
use think\Exception;

class ClubService
{
    private $clubDao;

    public function __construct()
    {
        $this->clubDao = new ClubDao();
    }

    // 创建社团
    public function createClub($data)
    {
        try {
            $club = $this->clubDao->createClub($data);

            if (!$club) {
                throw new Exception('创建社团失败');
            }

            return $club;
        } catch (\Exception $e) {
            Log::error("创建社团失败: " . $e->getMessage());
            throw new Exception('系统异常，请稍后再试');
        }
    }

    // 获取社团详情
    public function getClubDetails($clubId)
    {
        try {
            $club = $this->clubDao->getClubById($clubId);

            if (!$club) {
                throw new Exception('社团不存在');
            }

            // 可扩展：获取成员、活动等信息
            $leader = $club->leader;  // 通过模型关联获取

            return [
                'club'   => $club,
                'leader' => $leader,
            ];
        } catch (\Exception $e) {
            Log::error("获取社团详情失败: " . $e->getMessage());
            throw new Exception('系统异常，请稍后再试');
        }
    }

    // 获取所有社团
    public function getAllClubs()
    {
        try {
            return $this->clubDao->getAllClubs();
        } catch (\Exception $e) {
            Log::error("获取所有社团失败: " . $e->getMessage());
            throw new Exception('系统异常，请稍后再试');
        }
    }

    // 更新社团信息
    public function updateClub($clubId, array $data)
    {
        try {
            $result = $this->clubDao->updateClub($clubId, $data);

            if ($result === false) {
                throw new Exception('更新社团失败');
            }

            return $result;
        } catch (\Exception $e) {
            Log::error("更新社团失败: " . $e->getMessage());
            throw new Exception('系统异常，请稍后再试');
        }
    }

    // 删除社团
    public function deleteClub($clubId)
    {
        try {
            $result = $this->clubDao->deleteClub($clubId);

            if (!$result) {
                throw new Exception('删除社团失败');
            }

            return $result;
        } catch (\Exception $e) {
            Log::error("删除社团失败: " . $e->getMessage());
            throw new Exception('系统异常，请稍后再试');
        }
    }
}
